<template>
    <div>
        <!---->
        <alert-dialog :visible.sync="showUploadDialog" :title="$t('common.complaintUserUp')" width="560px">
            <el-form ref="uploadForm" :model="uploadForm" :rules="uploadFormRules"
                :label-width="$i18n.locale === 'zhCN' ? '100px' : '150px'" label-position="right">
                <!--选择-->
                <el-form-item :label="$t('common.select') + ' : '" prop="type">
                    <el-select v-model="uploadForm.type" @change="handleUploadTypeChange" style="width: 100%">
                        <el-option value="1" :label="$t('common.addOne')">{{ $t('common.addOne') }}</el-option><!--单个新增-->
                        <el-option value="2" :label="$t('common.addBatch')">{{ $t('common.addBatch')
                        }}</el-option><!--批量导入-->
                    </el-select>
                </el-form-item>
                <!--手机号-->
                <el-form-item :label="$t('common.phoneNum') + ' : '" prop="phone" v-if="uploadForm.type === '1'">
                    <el-input v-model="uploadForm.phone" :placeholder="$t('common.phoneNum')" maxlength="11"></el-input>
                </el-form-item>
                <!--导入-->
                <el-form-item :label="$t('common.import') + ' : '" prop="phoneList" v-if="uploadForm.type === '2'">
                    <el-button @click="handleSelectFile" type="primary" size="mini">{{ $t('common.chooseFile')
                    }}</el-button><!--选择文件-->
                    <el-button @click="downloadTemplate" type="text">{{ $t('common.downloadTemplateExcel')
                    }}</el-button><!--下载导入模板-->
                    <input ref="uploadFile" @change="handleFileChange" style="display: none" type="file"
                        accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
                    <div>{{ uploadForm.excelFile }}</div>
                </el-form-item>

            </el-form>
            <p v-if="uploadForm.errorMsg" class="color_red">* {{ uploadForm.errorMsg }}</p>
            <div slot="footer">
                <el-button @click="showUploadDialog = false;">{{ $t('common.cancel') }}</el-button><!--取消-->
                <el-button @click="submitUpload" type="primary">{{ $t('common.confirm') }}</el-button><!--确认-->
            </div>
        </alert-dialog><!--上传黑名单弹框end-->

    </div>
</template>
<script>
import alertDialog from '@/components/alert-dialog';
import mixinReadExcel from '@/service/mixin-read-excel';

export default {
    mixins: [mixinReadExcel],

    components: {
        alertDialog,
    },
    data() {
        return {
            showUploadDialog: false,
            uploadForm: {
                type: '1',
                phoneList: [],
                phone: '',
                excelFile: '未选择任何文件', // 接收上传的excel文件名称
                errorMsg: '', // 错误提示
                file: ''
            },
            uploadFormRules: {
                type: [
                    { required: true, message: this.$t('verify.plsChoose') }, // 请选择
                ],
                file: [
                    { required: true, message: this.$t('verify.plsImportData') }, // 请导入数据
                ],
                phoneList: [
                    { required: true, message: this.$t('verify.plsImportData') }, // 请导入数据
                ],
                phone: [
                    { required: true, pattern: /^09[0-9]{9}$/, message: this.$t('verify.plsInputCorrectNum'), trigger: 'blur' }, // 请输入0开头的10位数字
                ],
            },
        }

    },
    methods: {
        // 下载模板
        downloadTemplate() {
            window.open('/complaintUsers.xls');
        },
         // 打开新增黑名单弹框
         showUpload() {
            this.uploadForm.excelFile = this.$t('common.notChooseFile'); // 初始化提示为--未选择任何文件
            this.uploadForm.type = '1';
            this.uploadForm.phoneList = [];
            this.uploadForm.phone = '';
            this.uploadForm.errorMsg = '';
            this.uploadForm.userName = '';
            this.showUploadDialog = true;
            this.$nextTick(() => {
                const form = this.$refs.uploadForm;
                form && form.clearValidate();
            });
        },
        submitUpload() {
            const form = this.$refs.uploadForm;
            form.validate((val) => {
                if (val) {
                    const user = this.$storage.get('user');
                    const { phone,  phoneList, type } = this.uploadForm;
                    // 上传数据
                    const params = {
                        company:user.companyName,
                        domain:user.domain
                    };
                    //单挑新增
                    if ('1' === type) {
                        params.operatorId = user.id;
                        params.operatorName = user.username;
                        params.phone = phone;
                        this.$api.collection.removeUnEndOrderInfo(params, { showDefaultError: false }).then(res => {
                            const { status, msg } = res;
                            if ('1' === status) {
                                this.$message.success(this.$t('common.successfulOperation')); // 操作成功
                                this.showUploadDialog = false;
                                this.getTableData();
                            } else {
                                this.$alert(msg, {
                                    type: 'warning',
                                    confirmButtonText: this.$t('common.confirm'),
                                });
                            }
                        });
                    } else if ('2' === type) {
                        //文件上传到日
                        if (phoneList.length === 0) {
                            this.$message.warning(this.$t('verify.plsCheckFile')); // 请检查文件数据
                            return;
                        }
                        if (phoneList.length > 3000) {
                            this.uploadForm.errorMsg = this.$t('verify.maxImportOnce', { count: 3000 }); // 单次导入最多3000个
                            return;
                        }
                        params.creatorId = user.id;
                        params.creatorName = user.username;
                        params.phone = phoneList.join(',');
                        this.$api.collection.removeUnEndOrderInfo(params).then(res => {
                            const { status, data } = res;
                            if ('1' === status) {
                                this.$message.success(this.$t('common.successfulOperation')); // 操作成功
                                this.showUploadDialog = false;
                            }
                        });
                        
                        }

                    }
            });
            
        },
        // 改变新增方式时，清除校验
        handleUploadTypeChange() {
            const form = this.$refs.uploadForm;
            form && form.clearValidate();
            this.uploadForm.errorMsg = '';
        },
        // 打开文件选择
        handleSelectFile() {
            const uploadFile = this.$refs.uploadFile;
            uploadFile.click();
        },
        // 当上传文件时
        handleFileChange(event) {
            const ele = event.target || event.srcElement;
            if (ele.files && ele.files.length) {
                const file = ele.files[0];
                ele.value = '';
                this.uploadForm.excelFile = file.name;
                this.readExcelFile(file, { header: ['phone'] }).then(data => {
                    console.warn(data,'dasdasd')
                    const list = [];
                    const regPhone = /^09[0-9]{9}$/; // 手机号校验正则
                    data.forEach((item, index) => {
                        const { phone } = item;
                        console.warn(phone, index)
                        if (index != 0&&regPhone.test(phone)) {
                            list.push(phone);
                        }
                    });
                    console.warn(list)
                    this.uploadForm.phoneList = list;
                });
            }
        },
    }
}
</script>